import React, { useState, useCallback } from "react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import { UploadFileAPI } from "@/api/uploading";
import { useToast } from "@/components/ui/use-toast";
import {
  Plus,
  Trash2,
  BookOpen,
  UploadCloud,
  Image as ImageIcon,
  X,
  Loader2,
} from "lucide-react";

// Simple UUID generator function
const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
};

export default function AcceptanceRequirementsTab({
  scheme,
  onUpdate,
  isLoading,
}) {
  const { toast } = useToast();
  const [isUploading, setIsUploading] = useState(false);

  const acceptanceCriteria = scheme.acceptanceCriteria || [];
  const acceptancePhotos = scheme.acceptancePhotos || [];

  const handleAddItem = () => {
    const newItem = {
      id: generateId(),
      issueName: "",
      details: "",
      remark: "",
    };
    onUpdate({ acceptanceCriteria: [...acceptanceCriteria, newItem] });
  };

  const handleRemoveItem = (id) => {
    const updatedItems = acceptanceCriteria.filter((item) => item.id !== id);
    onUpdate({ acceptanceCriteria: updatedItems });
  };

  const handleItemChange = (id, field, value) => {
    const updatedItems = acceptanceCriteria.map((item) =>
      item.id === id ? { ...item, [field]: value } : item
    );
    onUpdate({ acceptanceCriteria: updatedItems });
  };

  const handleImageUpload = async (event) => {
    const files = event.target.files;
    if (!files || files.length === 0) return;

    setIsUploading(true);
    try {
      const uploadPromises = Array.from(files).map(async (file) => {
        const res = await UploadFileAPI.upload(file);
        // 返回完整的上传信息对象
        return res.data;
      });

      const results = await Promise.all(uploadPromises);

      onUpdate({ acceptancePhotos: [...acceptancePhotos, ...results] });

      toast({
        title: "上传成功",
        description: `${files.length} 张图片已成功上传。`,
        variant: "success",
      });
    } catch (error) {
      console.error("图片上传失败:", error);
      toast({
        title: "上传失败",
        description: "图片上传过程中发生错误，请稍后重试。",
        variant: "destructive",
      });
    } finally {
      setIsUploading(false);
    }
  };

  const handleRemoveImage = (id) => {
    const updatedPhotos = acceptancePhotos.filter((photo) => photo.id !== id);
    onUpdate({ acceptancePhotos: updatedPhotos });
  };

  if (isLoading) {
    return (
      <div className="flex justify-center items-center h-64">
        <Loader2 className="w-8 h-8 animate-spin text-gray-400" />
      </div>
    );
  }

  return (
    <div className="space-y-6">
      <Card>
        <CardHeader>
          <div className="flex justify-between items-center">
            <div>
              <CardTitle className="flex items-center gap-2">
                <BookOpen className="w-6 h-6 text-blue-600" />
                验收要求列表
              </CardTitle>
              <CardDescription className="mt-2">
                以表格形式管理详细的验收内容和标准。
              </CardDescription>
            </div>
            <Button onClick={handleAddItem}>
              <Plus className="mr-2 h-4 w-4" /> 添加验收项
            </Button>
          </div>
        </CardHeader>
        <CardContent>
          <div className="border rounded-md">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead className="w-[5%] text-center">序号</TableHead>
                  <TableHead className="w-[30%]">验收内容</TableHead>
                  <TableHead className="w-[40%]">验收标准/质量</TableHead>
                  <TableHead className="w-[20%]">备注</TableHead>
                  <TableHead className="w-[5%] text-center">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {acceptanceCriteria.length > 0 ? (
                  acceptanceCriteria.map((item, index) => (
                    <TableRow key={item.id}>
                      <TableCell className="text-center">{index + 1}</TableCell>
                      <TableCell>
                        <Textarea
                          value={item.issueName || ""}
                          onChange={(e) =>
                            handleItemChange(
                              item.id,
                              "issueName",
                              e.target.value
                            )
                          }
                          placeholder="例如：基础外观质量"
                          className="min-h-[80px]"
                        />
                      </TableCell>
                      <TableCell>
                        <Textarea
                          value={item.details || ""}
                          onChange={(e) =>
                            handleItemChange(item.id, "details", e.target.value)
                          }
                          placeholder="例如：表面平整、无裂缝、无蜂窝麻面"
                          className="min-h-[80px]"
                        />
                      </TableCell>
                      <TableCell>
                        <Textarea
                          value={item.remark || ""}
                          onChange={(e) =>
                            handleItemChange(item.id, "remark", e.target.value)
                          }
                          placeholder="选填"
                          className="min-h-[80px]"
                        />
                      </TableCell>
                      <TableCell className="text-center">
                        <Button
                          variant="ghost"
                          size="icon"
                          onClick={() => handleRemoveItem(item.id)}
                          className="text-red-500 hover:text-red-700"
                        >
                          <Trash2 className="h-4 w-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  ))
                ) : (
                  <TableRow>
                    <TableCell colSpan={5} className="h-24 text-center">
                      暂无验收要求，请点击 "添加验收项" 按钮开始。
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <UploadCloud className="w-6 h-6 text-green-600" />
            上传验收照片
          </CardTitle>
          <CardDescription>
            上传与本次验收相关的现场照片作为佐证材料。
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-center w-full">
            <label
              htmlFor="acceptance-photo-upload"
              className="flex flex-col items-center justify-center w-full h-32 border-2 border-gray-300 border-dashed rounded-lg cursor-pointer bg-gray-50 hover:bg-gray-100"
            >
              <div className="flex flex-col items-center justify-center pt-5 pb-6">
                <UploadCloud className="w-8 h-8 mb-4 text-gray-500" />
                <p className="mb-2 text-sm text-gray-500">
                  <span className="font-semibold">点击上传</span>{" "}
                  或拖拽文件到此处
                </p>
                <p className="text-xs text-gray-500">
                  支持PNG, JPG, GIF等图片格式
                </p>
              </div>
              <input
                id="acceptance-photo-upload"
                type="file"
                className="hidden"
                onChange={handleImageUpload}
                multiple
                accept="image/*"
                disabled={isUploading}
              />
            </label>
          </div>
          {isUploading && (
            <div className="flex items-center justify-center mt-4 text-sm text-gray-600">
              <Loader2 className="w-4 h-4 mr-2 animate-spin" />
              正在上传中...
            </div>
          )}

          {acceptancePhotos.length > 0 && (
            <div className="mt-6">
              <h4 className="font-semibold mb-3" onClick={() => {}}>
                已上传图片:
              </h4>
              <div className="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4">
                {acceptancePhotos.map((photo) => (
                  <div key={photo.docId} className="relative group">
                    <a
                      href={photo.docUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      <img
                        src={photo.docUrl}
                        alt={photo.docName || "验收照片"}
                        className="w-full h-32 object-cover rounded-md border border-gray-200"
                      />
                    </a>
                    <button
                      onClick={() => handleRemoveImage(photo.docId)}
                      className="absolute top-1 right-1 bg-red-600 text-white rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity"
                    >
                      <X className="w-3 h-3" />
                    </button>
                    <div className="absolute bottom-0 left-0 right-0 bg-black bg-opacity-50 text-white text-xs p-1 truncate rounded-b-md">
                      {photo.docName}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}
